<template>
  <div class="full-screen">
    <div id="map" class="full-screen"></div>
    <div class="container">
      <el-form ref="form" class="form-login" :model="form" label-width="80px">
        <h4>{{$project.title}}</h4>
        <el-form-item>
          <el-input @keyup.enter.native="handleLogin" v-model="form.account" prefix-icon="el-icon-user-solid">
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-input @keyup.enter.native="handleLogin" v-model="form.password" type="password"
            prefix-icon="el-icon-unlock" show-password></el-input>
        </el-form-item>
        <!-- <el-form-item>
          <el-col :span="16">
            <el-input v-model="form.code" prefix-icon="el-icon-key" @keyup.enter.native="handleLogin"></el-input>
          </el-col>
          <el-col :span="8">
            <el-image :src="imageCode" fit="fill" class="img-code" @click="getCodeImage"></el-image>
          </el-col>
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" class="btn" @click="handleLogin">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { randomNum } from "@/utils";
import loginApi from "@/api/Login";
import { Base64 } from "js-base64";
import db from "../../utils/localstorage";

export default {
  data() {
    this.earth = null;
    this.viewer = null;
    return {
      imageCode: "",
      form: {
        account: "admin",
        password: "123123",
        code: "",
        tenantView: "0000", //显示用的
        tenant: Base64.encode("0000"),
        key: randomNum(24, 16),
        grantType: "captcha",
      },
    };
  },
  mounted() {
    let me = this;
    // this.getCodeImage();

    me.earth = new Earth();
    me.viewer = me.earth.initMap('map', {
      imageryProvider: new Cesium.SingleTileImageryProvider({
        url: "static/images/map/s_512.jpg"
      })
    })

    /**
     * 地球自转
     */
    function rotation(bool) {
      let _rota = null;
      function rotate() {
        let a = .025;
        let t = Date.now();
        let n = (t - _rota) / 1e3;
        _rota = t;
        me.viewer.scene.camera.rotate(Cesium.Cartesian3.UNIT_Z, -a * n);
      }
      if (bool) {
        me._rota = Date.now();
        me.viewer.clock.onTick.addEventListener(rotate);
      } else {
        me.viewer.clock.onTick.removeEventListener(rotate);
      }
    }
    rotation(true);


    // 初始视角
    let startViewer = {
      poisiton: { longitude: 121.897688, latitude: 48.374499, height: 7500000 },
      euler: { heading: 0, pitch: -58, roll: 0 }
    }

    let info = { ...startViewer.poisiton, ...startViewer.euler }
    me.goAngleView(me.viewer, info);
  },
  methods: {
    /**
     * 三维相机定位
     * @param { Object } param 
     */
    goAngleView(_viewer, param) {
      _viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(parseFloat(param.longitude), parseFloat(param.latitude), parseFloat(param.height)),
        orientation: {
          heading: Cesium.Math.toRadians(parseFloat(param.heading)), // east, default value is 0.0 (north)
          pitch: Cesium.Math.toRadians(param.pitch),    // default value (looking down)
          roll: param.roll                           // default value
        },
        duration: 3
      });
    },
    handleLogin() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // this.onSubmit();
          this.$router.push("/home");
        } else {
          return false;
        }
      });
    },
    onSubmit() {
      this.loading = true;
      const that = this;
      let tenant = Base64.encode(this.form.tenantView);
      db.save("TENANT", tenant);
      this.$store.commit("account/setTenant", this.form.tenant);
      loginApi
        .login(this.form, {
          tenant: this.form.tenant,
          "X-isTenant": false,
        })
        .then((response) => {
          let res = response.data;
          if (res.isSuccess) {
            db.save("TOKEN", res.data.token);
            db.save("USER", res.data);
            that.$store.commit("account/setToken", res.data.token);
            that.$router.push("/home");
          } else {
            that.getCodeImage();
          }
        })
        .catch(() => {
          that.getCodeImage();
        })
        .finally(() => (that.loading = false));
    },
    getCodeImage() {
      loginApi
        .getCaptcha(this.form.key)
        .then((response) => {
          const res = response.data;
          if (res.byteLength <= 100) {
            this.$message({
              message: "系统维护中，请稍微再试~",
              type: "error",
            });
          }
          return (
            "data:image/png;base64," +
            btoa(
              new Uint8Array(res).reduce(
                (data, byte) => data + String.fromCharCode(byte),
                ""
              )
            )
          );
        })
        .then((res) => {
          this.imageCode = res;
        })
        .catch((e) => {
          if (e.toString().indexOf("429") !== -1) {
            this.$message({
              message: "获取验证码过于频繁，请1分钟后再试",
              type: "error",
            });
          } else {
            this.$message({
              message: "获取图形验证码失败",
              type: "error",
            });
          }
        });
    },
  },
  destroyed () {
    this.earth.destroy();
  },
};
</script>

<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;

  position: absolute;
  top: 0;
  left: 0;
  // background-color: #000;
  // background-image: url("../../assets/images/earth-bg.jpg"),
  //   url("../../assets/images/dark.svg"), url("../../assets/images/xk.webp");
  // background-position: bottom right, bottom right, top right;
  // background-size: 1280px 463px, 1164px 380px, cover;
  // background-repeat: no-repeat, no-repeat, no-repeat;
  // background-blend-mode: lighten, normal, normal;
  // -webkit-font-smoothing: subpixel-antialiased;
}

h4 {
  font-size: 30px;
  padding-left: 80px;
  text-align: center;
  color: #fff;
}

.form-login {
  width: 450px;
}

.btn {
  width: 100%;
  margin: 5px 0 !important;
}

.img-code {
  vertical-align: middle;
  border-style: none;
  filter: invert(1);
}

.img-code:hover {
  cursor: pointer;
}
</style>